<template>
  <herin-container title="带班领导及井下人员监测" :delay="1">
    <template #content>
      <div class="personnel-monitoring">
        <!-- 带班 -->
        <div class="lead-wrap">
          <div class="lead-left">{{currentClassName}}</div>
          <div :class="['lead-right', (shiftLeaderInfo?.data && shiftLeaderInfo?.data.length > 2) ? 'lead-right-scroll' : '']" >
            <div
              v-for="(p, index) in shiftLeaderInfo?.data"
              :key="index"
              class="name-item"
              @click="sendMessage(p.userName)"
            >
              <img class="person" src="@/assets/img/dispath/person.png" />
              <div class="name">{{ p.userName }}</div>
            </div>
          </div>
        </div>

        <!-- 井下人员 -->
        <div class="under-person">
          <div class="under-person1">
            <span>井下人员<span class="underperson-num"><span :class="['tag', setclass(inwellNum)]">{{inwellNum}}</span>/850</span>人</span>
          </div>
          <div class="under-person1">
            <span>入井超时<span class="moretime-num" style="color:#FFD101">{{overTimeNum}}</span>人</span>
          </div>
        </div>

        <!-- 分析 -->
        <div class="anaiyse-person">
          <div class="anaiyse-person1">
            <div>
            <div v-if='index'>人员类型分析排名</div>
            <div v-else>人员类型分析</div>
          </div>
          <div class="buttonbox">
            <div
              v-for="(item,index) in tabList"
              :key="index"
              :class="{'active':activeIndex === index}"
              style="cursor:pointer"
              @click="changeView(index)">{{item}}</div>
          </div>
          </div>
          <div class="anaiyse-chert">
            <CarLine v-if="tabList[activeIndex] === '趋势'" :carLinedata="carLinedata"></CarLine>
            <PersonSortort v-else :personTypeLists="personTypeLists"></PersonSortort>
          </div>
        </div>

        <!-- 人员列表 -->
        <div class="underground-personnel">
          <div class="personnel-title">
            <div>人员列表</div>
          </div>

          <div class="search-wrap">
            <HerinSelect
              v-model="selectType"
              class="herin-select"
              :options="selectOption"
              place-holder=""
              :height="28"
              :width="130"
              :showOptionscount="4"
              @HerinSelectChange="handleSelectChange"
            />
            <div class="input-box">
              <input v-model="searchInput" type="text" placeholder="搜索...">
              <i v-show="searchInput" class="el-icon el-icon-close" @click="clearInput" />
              <i class="el-icon el-icon-search" @click="handleSearch" />
            </div>
          </div>

          <div class="list-content">
            <div
              class="personnel-list"
              style="visibility:visible"
              v-infinite-scroll="scrollLists"
              infinite-scroll-distance="120"
              infinite-scroll-immediate="false"
            >
              <template v-if="personnelList.length > 0">
                <div
                  v-for="it in personnelList"
                  :key="it.cardNo"
                  :class="{ item: true, active: personnelStatus === it.id}"
                  @click="sendMessage(it.cardNo)"
                >
                  <div class="row">
                    <div class="name-type">
                      <span class="tag-button">{{ it.dutyName }}</span>
                      <span class="name">{{ it.userName }}</span>
                    </div>
                    <div class="long" :class="{alarm: isOverTimes(it.duration).isflag}">{{ srartDuration(it.duration) }}</div>
                  </div>
                  <div class="row last">
                    <div class="addr">
                      <img src="@/assets/img/dispath/addr.png">
                      <span class="station-name">{{ it.stationName }}</span>
                    </div>
                    <div>{{ it.inWellTime }}</div>
                  </div>
                </div>
              </template>
              <div v-else class="isCommonLists" style="padding-top:1.25rem;">暂无数据</div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </herin-container>
</template>

<script>
import HerinSelect from '@/components/herinselect/HerinSelect.vue';
import HerinContainer from '@/components/HerinContainer.vue';
import CarLine from '@/views/dispatch/common/carLine.vue';
import PersonSortort from '@/views/dispatch/common/personSortort.vue';

import { getShiftLeader, get24HoursChart, getPersonType, getAllType, queryPersonPage } from '@/api/item/dispatch/index';
import { xFormat } from '@/utils/date';
export default {

  components: {
    HerinContainer,
    CarLine,
    PersonSortort,
    HerinSelect
  },

  data() {
    return {
      personnum: 588,
      activeIndex: 0,
      index: 0,
      tabList: ['趋势', '类型'],
      showTipType: 'empty',
      searchInput: '',
      selectType: '全部工种',
      selectOption: [
        { label: '全部工种', value: '全部工种' }
      ],
      shiftLeaderInfo: {},
      carLinedata: [],
      personTypeLists: [],
      current: 0,
      personnelList: [],
      pages: 1,
      actionLoopTimer3S: null,
      actionLoopTimer1H: null
    };
  },

  computed: {
    isOverTimes() {
      return function(times) {
        const info = {};
        const dates = new Date();
        const currentDate = dates.getFullYear() + '-' + (dates.getMonth() + 1) + '-' + dates.getDate();

        const overTimes = new Date(`${currentDate} 08:00:00`).getTime();
        const paramsTimes = new Date(`${currentDate} ${times}`).getTime();

        if (overTimes > paramsTimes) {
          info['isflag'] = false;
          info['paramsTimes'] = paramsTimes;
          return info;
        } else {
          info['isflag'] = true;
          info['paramsTimes'] = paramsTimes;
          return info;
        }
      };
    },
    srartDuration() {
      return function(duration) {
        const list = duration.split(':');
        const str = '已入井 ' + list[0] + '小时 ' + list[1] + '分 ' + list[2] + '秒';
        return str;
      };
    },
    personnelStatus() {
      return this.$store.state.personnelStatus;
    },
    inwellNum() {
      return this.$store.state.inwellNum;
    },
    overTimeNum() {
      return this.$store.state.overTimeNum;
    },
    currentClassName() {
      let str = '';

      const dates = new Date();
      const currentDate = dates.getFullYear() + '-' + (dates.getMonth() + 1) + '-' + dates.getDate();
      const currentTimes = dates.getHours() + ':' + dates.getMinutes() + ':' + dates.getSeconds();

      const section0Times = new Date(`${currentDate} 00:00:00`).getTime();
      const section8Times = new Date(`${currentDate} 08:00:00`).getTime();
      const section16Times = new Date(`${currentDate} 16:00:00`).getTime();
      const section24Times = new Date(`${currentDate} 24:00:00`).getTime();

      const sectionCurrentTimes = new Date(`${currentDate} ${currentTimes}`).getTime();

      if (sectionCurrentTimes >= section0Times && sectionCurrentTimes < section8Times) {
        str = '零点班';
      }
      if (sectionCurrentTimes >= section8Times && sectionCurrentTimes < section16Times) {
        str = '八点班';
      }
      if (sectionCurrentTimes >= section16Times && sectionCurrentTimes < section24Times) {
        str = '四点班';
      }

      return str;
    }
  },
  created() {
    this.$store.dispatch('listeningEvents', { fn: this.setData, _this: this });
  },
  mounted() {
    this.queryPersonPage();

    this.startActionLoop3S(this.all3SFun);
    this.startActionLoop1H(this.get24HoursChart);
  },
  beforeDestroy() {
    this.$store.dispatch('closeListeningEvents', { fn: this.setData, _this: this });
    this.$store.commit('setData', { name: 'personnelStatus', value: null });

    this.actionLoopTimer3S && clearInterval(this.actionLoopTimer3S);
    this.actionLoopTimer3S = null;
    this.actionLoopTimer1H && clearInterval(this.actionLoopTimer1H);
    this.actionLoopTimer1H = null;
  },

  methods: {
    all3SFun() {
      this.getShiftLeader();
      this.getAllType();
      if (this.tabList[this.activeIndex] === '类型') {
        this.getPersonType();
      }
    },
    // 每隔 3S 循环查询数据
    startActionLoop3S(callback) {
      callback();
      this.actionLoopTimer3S = setInterval(callback, 3000);
    },
    // 每隔 1小时 循环查询
    startActionLoop1H(callback) {
      callback();
      // 3600000
      this.actionLoopTimer1H = setInterval(callback, 3600000);
    },
    changeView(index) {
      this.activeIndex = index;
      this.index = index;
      if (this.tabList[this.activeIndex] === '类型') {
        this.getPersonType();
      } else {
        this.get24HoursChart();
      }
    },
    // 获取所有工种
    async getAllType() {
      const res = await getAllType();
      if (res.data.code === 200) {
        const data = res.data.data.map(item => {
          return {
            label: item,
            value: item
          };
        });
        this.selectOption = [...[{ label: '全部工种', value: '全部工种' }], ...data];
      }
    },

    scrollLists() {
      if (this.current < this.pages) {
        this.current++;
        this.queryPersonPage();
      }
    },

    // 获取人员详情信息带分页
    async queryPersonPage() {
      // const copyLists = this.personnelList.splice(0);

      const params = {
        dutyName: this.selectType === '全部工种' ? '' : this.selectType,
        userName: this.searchInput,
        current: this.current,
        size: 100
      };
      this.showTipType = 'search';

      const res = await queryPersonPage(params);
      if (res.data.code === 200) {
        const resInfo = res.data.data;
        const data = [...this.personnelList, ...resInfo.records];
        const sortData = data.sort((a, b) => {
          if (this.isOverTimes(a.duration).isflag) {
            return this.isOverTimes(b.duration).paramsTimes - this.isOverTimes(a.duration).paramsTimes;
          } else {
            return b.inWellTime - a.inWellTime;
          }
        });
        this.personnelList = sortData;
        this.pages = resInfo.pages;
      }
    },

    clearInput() {
      this.searchInput = '';
      this.current = 0;
      this.personnelList = [];
      this.queryPersonPage();
    },

    handleSelectChange() {
      this.personnelList = [];
      this.current = 0;
      this.queryPersonPage();
    },

    handleSearch() {
      this.personnelList = [];
      this.current = 0;
      this.queryPersonPage();
    },

    setclass(val) {
      if (val <= 850) {
        return 'green';
      } else {
        return 'red';
      }
    },

    // 获取带班领导信息
    async getShiftLeader() {
      const res = await getShiftLeader();
      if (res.data.code === 200) {
        const data = res.data.data.sort((a, b) => {
          return b.inWellTime - a.inWellTime;
        });
        const info = {
          data
        };
        this.shiftLeaderInfo = info;
      }
    },

    // 获取24小时人数图表
    async get24HoursChart() {
      const res = await get24HoursChart();
      if (res.data.code === 200) {
        const data = res.data.data.map(item => {
          return {
            x: xFormat(item.x),
            y: item.y * 1,
            s: item.s
          };
        });
        this.carLinedata = data;
      }
    },

    // 获取人员构成信息
    async getPersonType() {
      const res = await getPersonType();
      if (res.data.code === 200) {
        const sortData = res.data.data.sort((a, b) => {
          if (a.dutyName !== '其他' && b.dutyName !== '其他') {
            return b.dutyNum - a.dutyNum;
          }
        });
        // 排序之后，取前5
        const before5List = sortData.slice(0, 5);
        const data = before5List.map(item => {
          return {
            proportion: (item.proportion.slice(0, -1)) * 1,
            dutyName: item.dutyName,
            dutyNum: item.dutyNum
          };
        });
        this.personTypeLists = data;
      }
    },

    sendMessage(id) {
      // 设置 personnelStatus 值
      this.$store.commit('setData', { name: 'personnelStatus', value: id });

      this.$store.dispatch('postToEngine', { sceneName: 'PERSONNEL', data: id });
    },

    setData(msg) {
      if (msg.data) {
        const { action, type, entityData } = msg.data;
        if (type === 'EPointPersonnel') {
          const { id } = entityData;
          if (action === 'OnHidePanel') {
            // 设置 personnelStatus 值
            this.$store.commit('setData', { name: 'personnelStatus', value: null });
          } else if (action === 'OnShowPanel') {
            // 设置 personnelStatus 值
            this.$store.commit('setData', { name: 'personnelStatus', value: id });

            this.goActivePosition();
          }
        }
        if (type === 'EPointMonitor') {
          if (action === 'OnHidePanel') {
            // 关闭视频弹窗
            this.$store.commit('setData', { name: 'videoInfo', value: {
              isVideo: false,
              name: '',
              status: '',
              videoLink: ''
            }});
          } else if (action === 'OnShowPanel') {
            const params = {
              'cameraIndexCode': entityData?.id,
              'cameraName': entityData?.monitorName,
              'status': entityData?.status
            };

            this.$store.dispatch('queryCameraUrl', { videoInfo: params });
          }
        }

        msg.resolve({ response: 'successs' }); // 必须执行 msg.resolve()
      }
    },
    // 滚动到指定位置
    goActivePosition() {
      if (this.personnelStatus !== null) {
        const index = this.personnelList.findIndex(item => item.id === this.personnelStatus);
        const activePosition = document.querySelector('.personnel-list');
        activePosition.scrollTop = index * 60;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.herin-container{
  position: relative;
  .personnel-monitoring{
    .lead-wrap{
      display: flex;
      // padding-right: .9375rem;
      justify-content: space-between;
      .lead-left{
        width: 1.25rem;
        height: 100%;
        color: #34C8FF;
        text-align: center;
        margin-right: 15px;
        color: #34C8FF;
        // font-size: 12px;
        background-color:rgba(#34C8FF, 0.3);
      }
      .lead-right{
        width: 18.75rem;
        white-space: nowrap;
        padding: 1rem 0;
        // display: flex;
        // justify-content: space-between;
        // align-items: center;
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: .25rem;
        .name-item{
          white-space: nowrap;
          display: inline-flex;
          width: 9.3125rem;
          height: 1.5625rem;
          justify-content: center;
          border-right: .0625rem solid gray;
            .person{
            width: 1.5625rem;
            height: 1.5625rem;
            margin-right: .625rem;
            }
            .name{
            color: #fff;
          }
        }
        .name-item:last-child{
          border-right: none;
        }
      }
      .lead-right-scroll{
        overflow-x: scroll;
        overflow-y: hidden;
      }
    }
  }

  .under-person{
    border-radius: .25rem;
    height: 2.5rem;
    display: flex;
    margin-top: .625rem;
    justify-content: space-between;
    align-items: center;
    font-size: .875rem !important;
    padding:0 .625rem;
    background-color: rgba(255, 255, 255, 0.1);
    .under-person1{
      color: #F8F8F8;
      .underperson-num,.moretime-num{
        margin-left: .9375rem;
        font-size: 1rem !important;
      }
    }
  }
  .green {
    color: $green !important;
  }
  .red {
    color: $red !important;

  }
  .anaiyse-person{
    .anaiyse-person1{
    display: flex;
    justify-content: space-between;
    margin: .3125rem 0;
    font-size: .75rem;
    color: #ADADAD;
    }
    .buttonbox{
      display: flex;
      align-items: center;
      div{
        font-size: .75rem;
        color: rgba(255, 255, 255, 100);
        margin:0 .1875rem;
        padding: 0 .3125rem;
        width: 2.125rem;
        text-align: center;
        height: 1rem;
        line-height: 1rem !important;
        background: rgba(232, 232, 232, 0.2);
      }
      .active{
        color: #02E4FF;
        background-color: rgba(2, 228, 255, 0.2);
      }
    }
  }

  // underground-personnel
  .underground-personnel{
      margin-top: .625rem;
      .personnel-title{
        display: flex;
        justify-content: space-between;
        font-size: $auxiliaryText;
        color:$light2Grey;
        height: 0.875rem;
        line-height: 0.875rem;
        .num{
          color: $lightGrey;
        }
      }
      .search-wrap{
        display: flex;
        justify-content: space-between;
        margin-top: 0.625rem;
        .input-box{
          width: 11.875rem;
          height: 1.75rem;
          border: .0625rem solid rgba($color: #FFFFFF, $alpha: 0.2);
          border-radius: 0.25rem;
          position: relative;
          text-align: left;
          box-sizing: border-box;
          input{
            width: 72%;
            height: 100%;
            margin: 0 0.625rem;
            border: none;
            font-size: 0.75rem;
            color: rgba($color:$white, $alpha: 0.9);
            background-color: transparent;
            outline-width: 0rem;
          }
          input::-webkit-input-placeholder{
            font-size: 0.75rem;
            color: $secondaryTextColor;
          }
          .el-icon{
            display: inline-block;
            width: 0.875rem;
            height: 0.875rem;
            line-height: 0.875rem;
            font-size: 0.75rem;
            cursor: pointer;
            color: rgba($color: $white, $alpha: 0.5);
            position: absolute;
            top: 0.4375rem;
            &-close{
              right: 1.375rem;
            }
            &-search{
              right: .25rem;
              font-size: .75rem;
            }
          }
        }
      }
      .list-content{
        position: relative;
        .personnel-list{
          width: calc(100% + 10px);
          padding-right: 0.4375rem;
          height: 7.5rem;
          overflow: auto;
          // margin-top: 0.625rem;
          .item{
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            height: 3.75rem;
            padding: 0.625rem 0.625rem 0.625rem 0;
            border-bottom: 0.0625rem solid rgba($color: #ffffff, $alpha: 0.1);
            div{
              cursor: pointer;
            }
            &.active{
              background-color: $itemActiveBg;
            }
            // &:hover{
            //   background-color: $itemActiveBg;
            // }
            .row{
              display: flex;
              justify-content: space-between;
              align-items: center;
              font-size: $auxiliaryText;
              height: 0.875rem;
              line-height: 0.875rem;
              .name-type{
                .name{
                  color: $light3Grey;
                  font-size: $commonContentText;
                  margin-left: 0.625rem;
                }
                .tag-button{
                  @include tag-btn();
                }
              }
              .long{
                color: $lightGrey;
                &.alarm{ color: $red; }
              }
              .addr{
                img{
                  width: 0.75rem;
                  height: 0.75rem;
                  margin-right: 0.25rem;
                }
              }
              &.last{
                color: $lightGrey;
                .station-name {
                  width: 11.125rem;
                  overflow:hidden;
                  text-overflow:ellipsis;
                  display: inline-block;
                  white-space: nowrap;
                }
              }
            }
          }
        }
      }
  }
}
</style>
